#include "XTcpTask.h"
#include <event2/event.h>
#include <event2/bufferevent.h>
#include<iostream>
#include <string.h>
using namespace std;

XTcpTask::XTcpTask(int fd)
{
    XTask::setFd(fd);
}

XTcpTask::~XTcpTask()
{

}

/**
 * @fn       XFtpServerCMD::Init
 * @brief    初始化任务 运行在子线程中
 * @param[in]
 * @param[out]
 * @retval
 */
void XTcpTask::eventCallBack(struct bufferevent *bev, short what, void *arg)
{
    XTcpTask *cmd = (XTcpTask*)arg;

    //如果对方网络断掉，或者机器死机有可能收不到BEV_EVENT_EOF数据
    if (what & (BEV_EVENT_EOF | BEV_EVENT_ERROR | BEV_EVENT_TIMEOUT))
    {
        cout << "BEV_EVENT_EOF | BEV_EVENT_ERROR |BEV_EVENT_TIMEOUT" << endl;
        cout << "timeout or disconnect"<<endl;
        bufferevent_free(bev);
        delete cmd;
    }
}

/**
 * @fn       XFtpServerCMD::Init
 * @brief    初始化任务 运行在子线程中
 * @param[in]
 * @param[out]
 * @retval
 */
void XTcpTask::readCallBack(bufferevent * bev, void *arg)
{

    char data[1024] = {0};
    while(true)
    {
        int len = bufferevent_read(bev, data, sizeof(data) - 1);
        if (len <= 0)
        {
            break;
        }
        data[len] = '\0';
        cout << data << endl;
        bufferevent_write(bev, data, sizeof(data) - 1);
    }
}

/**
 * @fn       XFtpServerCMD::Init
 * @brief    初始化任务 运行在子线程中
 * @param[in]
 * @param[out]
 * @retval
 */
bool XTcpTask::Init()
{
    cout << "XTcpTask::Init()" << endl;
    //监听socket bufferevent
    bufferevent * bev = bufferevent_socket_new(m_base, m_fd, BEV_OPT_CLOSE_ON_FREE);
    bufferevent_setcb(bev, readCallBack, 0, eventCallBack, this);
    bufferevent_enable(bev, EV_READ | EV_WRITE);

    /* 添加超时 */
    timeval rt = {10,0};
    bufferevent_set_timeouts(bev, &rt, 0);
    return true;
}

